package cn.core.conf.listener;

import cn.core.conf.bo.ConfBOAO;
import cn.core.conf.eo.Conf;
import cn.core.conf.mapper.ConfMapper;
import cn.core.conf.qo.ConfQO;
import cn.core.tool.event.CoreDataEvent;
import cn.core.tool.exception.CoreException;
import cn.core.tool.util.CoreTool;
import com.google.gson.reflect.TypeToken;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.LinkedHashMap;

/**
 * 系统配置 事件监听器
 */
@Log4j2
@Service
public class ConfEventListener {

  @Resource
  private ConfMapper confMapper;

  /**
   * 配置类型 配置环境 >>> 获取所有配置键值信息
   */
  @EventListener(condition = "#coreDataEvent.eventKey == 'getAllConfMapInfo'")
  public void getAllConfMapInfo(CoreDataEvent coreDataEvent) throws Exception {
    try {
      if (CoreTool.isNullStr(coreDataEvent.getParam())) {
        throw new CoreException("参数错误，配置类型、配置环境为空！");
      }
      ConfBOAO confBOAO = coreDataEvent.getParam(new TypeToken<ConfBOAO>(){});
      if (CoreTool.isNullEo(confBOAO)) {
        throw new CoreException("参数错误，配置类型、配置环境为空！");
      }
      Collection<Conf> confSet = confMapper.query(new ConfQO().setConfType(confBOAO.getConfType()).setConfEnv(confBOAO.getConfEnv()));
      if (CoreTool.isNotEmpty(confSet)) {
        LinkedHashMap<String, String> confMapInfo = new LinkedHashMap<>();
        for (Conf eo : confSet) {
          confMapInfo.put(eo.getConfKey(), eo.getConfValue());
        }
        coreDataEvent.setData(confMapInfo);
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  /**
   * 配置类型 配置环境 配置标识 >>> 获取配置信息
   */
  @EventListener(condition = "#coreDataEvent.eventKey == 'getConfInfo'")
  public void getConfInfo(CoreDataEvent coreDataEvent) throws Exception {
    try {
      if (CoreTool.isNullStr(coreDataEvent.getParam())) {
        throw new CoreException("参数错误，配置类型、配置环境、配置标识为空！");
      }
      ConfBOAO confBOAO = coreDataEvent.getParam(new TypeToken<ConfBOAO>(){});
      if (CoreTool.isNullEo(confBOAO)) {
        throw new CoreException("参数错误，配置类型、配置环境、配置标识为空！");
      }
      Collection<Conf> confSet = confMapper.query(new ConfQO().setConfType(confBOAO.getConfType()).setConfEnv(confBOAO.getConfEnv()).setConfKey(confBOAO.getConfKey()));
      if (CoreTool.isNotEmpty(confSet)) {
        coreDataEvent.setData(confSet.iterator().next().getConfValue());
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
